<template>
  <div class="product-fault-library-table">
    <div class="product-fault-library-table-group">
      <el-dropdown trigger="click">
        <span class="el-dropdown-link cur-point">
          {{ $t('common.base.moreOperator') }}
          <i class="iconfont icon-fdn-select"></i>
        </span>
        <el-dropdown-menu slot="dropdown">
          <el-dropdown-item>
            <div @click="handleExport">{{ $t('common.base.exportAll') }}</div>
          </el-dropdown-item>
        </el-dropdown-menu>
      </el-dropdown>
      <span class="el-dropdown-link cur-point ml_20" @click="handleSelectColumn">
        {{ $t('common.base.choiceCol') }}
        <i class="iconfont icon-fdn-select"></i>
      </span>
    </div>

    <el-table ref="tableRef" v-loading="listLoading" header-row-class-name="common-list-table-header__v2" :data="disposeFormListViewTime(dataList, columns)" stripe border>
      <template slot="empty">
        <BaseListForNoData v-show="!listLoading" :notice-msg="$t('common.base.tip.noData')"></BaseListForNoData>
      </template>

      <template v-for="column in columns">
        <el-table-column v-if="column && column.show" show-overflow-tooltip :align="column.align" :key="column.field" :label="column.displayName" :min-width="column.minWidth" :width="column.width" :prop="column.field">
          <template slot-scope="scope">
            <template v-if="column.field === 'executorName'">
              <template v-if="isOpenData && scope.row && scope.row.executorStaffId">
                <open-data type="userName" :openid="scope.row.executorStaffId"></open-data>
              </template>
              <template v-else>
                {{ scope.row.executorName }}
              </template>
            </template>
            <template v-else-if="column.field === 'taskNo'">
              <span class="link" @click="jumpTaskDetail(scope.row.taskId)">{{ scope.row.taskNo }}</span>
            </template>
            <template v-else>
              {{ $formatFormField(column, scope.row) }}
            </template>
          </template>
        </el-table-column>
      </template>
    </el-table>

    <!-- 分页 -->
    <BaseAddOnPagination :paginationInfo="paginationInfo" @pageJump="jump" @sizeChange="handleSizeChange" />

    <!-- 选择列 -->
    <biz-select-column ref="advanced" @save="saveColumnStatus" />

    <!-- 导出 -->
    <base-export-group
      ref="exportRef"
      :alert="exportAlert"
      :columns="exportColumnList"
      :build-params="exportParamsBuild"
      :group="true"
      :validate="exportCountCheck"
      method="post"
      action="/excels/productDetail/faultRecord"
    />
  </div>
</template>
<script>
import { useFormTimezone } from 'pub-bbx-utils';
const { disposeFormListViewTime } = useFormTimezone();

import { isOpenData, toast, openAccurateTab } from '@src/util/platform';
import { PageRoutesTypeEnum } from 'pub-bbx-global/pageType/dist/enum/PageRoutesEnum'
import { storageGet, storageSet } from '@src/util/storage';
import { Message } from 'element-ui';
import i18n from '@src/locales';

// api
import {
  solutionGetFields, // 获取解决方案表单字段
} from '@src/api/Fault';
import { productFaultRecord } from '@src/api/ProductV2Api';
import { onMounted, ref, reactive, toRefs, computed, nextTick } from 'vue';

export default {
  name: 'product-fault-library-table',
  props: {
    shareData: {
      type: Object,
      default: () => ({}),
    },
  },
  setup(props) {
    const advanced = ref(null);
    const exportRef = ref(null);

    const state = reactive({
      listLoading: true,
      dataList: [],
      columns: [],
      paginationInfo: {
        pageSize: 10,
        pageNum: 1,
        totalItems: 0,
      },
    });

    // 固定字段
    const fixColumns = computed(() => {
      const arr = [
        {
          displayName: i18n.t('common.base.description1'),
          fieldName: 'faultDesc',
        },
        {
          displayName: i18n.t('common.form.preview.faultLibrary.concatLabel5'),
          fieldName: 'solutionDesc',
        },
        {
          displayName: i18n.t('common.fields.taskType.displayName'),
          fieldName: 'templateName',
        },
        {
          displayName: i18n.t('common.form.type.taskNo'),
          fieldName: 'taskNo',
        },
        {
          displayName: i18n.t('task.taskTypes.allot.taskExecutor'),
          fieldName: 'executorName',
        },
        {
          displayName: i18n.t('task.setting.taskAdditionalSetting.taskFinishTime'),
          fieldName: 'completeTime',
        },
      ].map(item => {
        return {
          ...item,
          field: item.fieldName,
          isSystem: 1,
          show: true,
        };
      });

      return arr;
    });

    const productInfo = computed(() => {
      return props.shareData?.product || {};
    });

    // 构建导出字段
    const exportColumnList = computed(() => {
      const systemInfo = {
        label: i18n.t('contract.list.systemInfoLabel'),
        value: 'systemChecked',
        columns: [...state.columns].map(item => {
          item.export = true;
          item.label = item.displayName;
          return item;
        }).filter(item => !!item.isSystem),
      };

      const customInfo = {
        label: i18n.t('common.paas.view.designer.workFlow.customInfo'),
        value: 'customChecked',
        columns: [...state.columns].map(item => {
          item.export = true;
          item.label = item.displayName;
          return item;
        }).filter(item => !item.isSystem),
      }
      let column = [systemInfo, customInfo].filter(item => {
        return item.columns && item.columns.length > 0;
      });

      return column;
    })

    // 构建表格选择列字段
    const buildColumns = async () => {
      // 获取缓存在本地的选择列配置
      const localStorageData = await getLocalStorageData();
      const columnStatus = localStorageData.columnStatus || [];

      const localColumns = columnStatus
        .map(i => (typeof i == 'string' ? { field: i, show: true } : i))
        .reduce((acc, col, currentIndex) => {
          acc[col.field] = {
            field: col,
            index: currentIndex,
          };
          return acc;
        }, {});

      let customFields = state.columns;
      if (Array.isArray(columnStatus) && columnStatus.length > 0) {
        // 有本地缓存--列表排序
        customFields = buildSortFields(customFields, localColumns);
      }

      const columns = customFields.map(col => {
        // 选择列配置 是否勾选（显示）&宽度
        let show = col.show === true;
        let width = col.width;
        let localField = localColumns[col.field]?.field || null;
        if (null != localField) {
          if (localField.width) {
            width = typeof localField.width == 'number' ? `${localField.width}px` : localField.width;
          }
          show = localField.show !== false;
        }

        col.show = show;
        col.width = width;
        col.minWidth = col.width || 150;
        return col;
      });

      state.columns = [];
      nextTick(() => {
        state.columns = columns;
      });
    };

    // 选择列排序
    const buildSortFields = (originFields = [], fieldsMap = {}) => {
      let fields = [];
      let unsortedFields = [];

      originFields.forEach(originField => {
        let { fieldName } = originField;
        let field = fieldsMap[fieldName];

        if (field) {
          let { index } = field;
          fields[index] = originField;
        } else {
          unsortedFields.push(originField);
        }
      });

      // 存储列数据之后，如果存在列被删除的情况，可能产生空值，需要过滤，否则其他地方没做判断会报错
      return fields.filter(v => v).concat(unsortedFields);
    };

    const fetchProductFaultRecord = async () => {
      try {
        const res = await productFaultRecord({
          productId: productInfo.value.id,
          pageNum: state.paginationInfo.pageNum,
          pageSize: state.paginationInfo.pageSize,
        });

        const { success, data, message } = res;
        if (!success) return toast(message, 'error');

        state.dataList = (data?.list || []).map(item => {
          let { solutionVO, ...other } = item;

          return {
            ...solutionVO,
            ...other,
          };
        });

        state.paginationInfo.totalItems = data.totalSize;
      } catch (err) {
        console.log('fetchProductFaultRecord => err', err);
      } finally {
        state.listLoading = false;
      }
    };

    const fetchFaultLibraryField = () => {
      try {
        state.listLoading = true;
        Promise.all([solutionGetFields()]).then(res => {
          if (!res[0].success) return toast(res[0].message, 'error');

          // 排除的字段
          let excludeField = ['attachment', 'autograph', 'info', 'separator', 'subSparePart', 'richtext'];
          // 动态字段
          let dynamicsColumns = (res[0]?.data || [])
            .filter(field => !excludeField.includes(field.formType) && !field.isSystem)
            .map(item => {
              return {
                ...item,
                field: item.fieldName,
              };
            });

          // 表头字段
          state.columns = [...fixColumns.value, ...dynamicsColumns];

          fetchProductFaultRecord();

          buildColumns();
        });
      } catch (err) {
        console.log('fetchFaultLibraryField => err', err);
      }
      // finally {
      //   state.listLoading = false;
      // }
    };

    // 切换分页
    const jump = pN => {
      state.paginationInfo.pageNum = pN;
      fetchProductFaultRecord();
    };

    const handleSizeChange = pageSize => {
      state.paginationInfo.pageSize = pageSize;
      state.paginationInfo.pageNum = 1;
      fetchProductFaultRecord();
    };

    // === 选择列
    // 获取本地localstorage
    const getLocalStorageData = () => {
      const dataStr = storageGet('product-fault-library-table', '{}');
      return JSON.parse(dataStr);
    };

    // 保存数据到本地localstorage
    const saveDataToStorage = (key, value) => {
      const data = getLocalStorageData();
      data[key] = value;
      storageSet('product-fault-library-table', JSON.stringify(data));
    };

    // 点击选择列
    const handleSelectColumn = () => {
      state.columns.forEach(item => {
        item.tableName = 'project';
      });
      advanced.value.open(state.columns);
    };

    // 保存选择列
    const saveColumnStatus = event => {
      let columns = event.data || [];
      state.columns = [];
      nextTick(() => {
        state.columns = columns.slice();
        saveColumnStatusToStorage();
      });
      Message.success(i18n.t('common.base.saveSuccess'));
    };

    // 保存选择列配置到本地
    const saveColumnStatusToStorage = () => {
      const localStorageData = getLocalStorageData();
      let columnsStatus = null;

      // 判断是否存储选择列
      const columnsList = state.columns.map(c => ({
        field: c.fieldName,
        show: c.show,
        width: c.width,
      }));

      if (localStorageData.columnStatus) {
        localStorageData.columnStatus = columnsList;
        columnsStatus = localStorageData.columnStatus;
      } else {
        columnsStatus = columnsList;
      }

      saveDataToStorage('columnStatus', columnsStatus);
    };

    // 点击导出
    const handleExport = () => {
      exportRef.value.open([], '', false);
    };

    // 导出提示
    const exportAlert = (result) => {
      toast(result.message, result.status === 0 ? 'success' : 'error');
    };

    // 构建导出参数
    const exportParamsBuild = (checkedMap, ids) => {
      let { customChecked, systemChecked } = checkedMap || {};
      return {
        // 产品名称
        productName: props?.shareData?.product?.name,
        // 系统字段
        systemFieldList: systemChecked,
        // 自定义字段
        customFieldList: customChecked,
        isExportAll: true,
        exportTotal: state.paginationInfo.totalItems || 0,
        productId: props?.shareData?.product?.id
      };
    };

    /**
     * @description 检测导出条数
     * @return {String | null}
     */
    const exportCountCheck = (ids, max) => {
      let exportAll = !ids || ids.length == 0;

      return exportAll && state.paginationInfo.totalItems > max
        ? i18n.t('common.base.tip.exportLimit', { max })
        : null;
    };

    const jumpTaskDetail = (taskId) => {
      let fromId = window.frameElement.getAttribute('id')
      openAccurateTab({
        type: PageRoutesTypeEnum.PageTaskView,
        key: taskId,
        fromId
      })
    }
    onMounted(() => {
      fetchFaultLibraryField();
    });

    return {
      advanced,
      exportRef,
      ...toRefs(state),
      disposeFormListViewTime,
      handleExport,
      handleSelectColumn,
      saveColumnStatus,
      jump,
      handleSizeChange,
      isOpenData,
      jumpTaskDetail,
      exportAlert,
      exportColumnList,
      exportParamsBuild,
      exportCountCheck
    };
  },
};
</script>
<style lang="scss" scoped>
.product-fault-library-table {
  padding: 12px;
  &-group {
    display: flex;
    justify-content: flex-end;
    margin-bottom: 12px;
    padding: 0;
  }
  .link {
    color: $color-primary-light-6;
    cursor: pointer;
    &:hover {
      text-decoration: underline;
    }
  }
}
</style>